package alioss

import (
	"encoding/json"
	"github.com/mjiulee/lego"
	"github.com/valyala/fasthttp"
)

func (t *AliOss) GetPolicyTokenHandler(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	ctxExt.Response.Header.Set("Content-type", "application/json")
	/*ctxExt.Response.Header.Set("Access-Control-Allow-Methods", "POST")
	ctxExt.Response.Header.Set("Access-Control-Allow-Origin", "*")*/

	requestByte := ctxExt.PostBody()

	type Request struct {
		CallbackParam
	}

	type Response struct {
		Code int `json:"code"`
		Msg int `json:"msg"`
		Data *PolicyToken `json:"data,omitempty"`
	}

	var request Request
	var response Response
	//request.CallbackUrl = "/api/mod/oss/alioss/oss_callback"
	//request.CallbackBodyType = "application/x-www-form-urlencoded"

	err := json.Unmarshal(requestByte, &request)
	if err != nil {
		ctxExt.ResponseWithStateCode200(100, err.Error())
		return
	}


	policyToken, err := t.GetPolicyToken(&request.CallbackParam)
	if err != nil {
		ctxExt.ResponseWithStateCode200(100, err.Error())
		return
	}

	response.Data = policyToken
	responseStr, err := json.Marshal(&response)
	if err != nil {
		ctxExt.ResponseWithStateCode200(100, err.Error())
		return
	}

	ctxExt.Response.SetStatusCode(200)

	ctxExt.Write(responseStr)
}
